<template>
	<view class="content">
	<!-- 清空浏览过按钮，仅在收藏模式下生效 -->
	<view v-if="props.isFav" class="clearHistory w-full text-right text-gray-600 text-sm p-1 pt-2 pr-3" @click="clearAllHistory">清空记录</view>
	<view class="t-goods-list" v-if="goodsList.data && goodsList.data.length>0">
			<view class="t-goods-item" v-for="(item,index) in goodsList.data" :key="index" @click="GoUrl('../shop_detail/shop_detail?pid='+item.id)">
				<image class="t-goods-img" :src="item.productimg"></image>
				<view class="t-goods-name"><text>{{item.productname}}</text></view>
				<!-- <view class="t-goods-desc"><text>{{item.goodsDesc}}</text></view> -->
				<!-- <view class="t-goods-tags" v-if="item.tags && item.tags.length>0">
					<view class="t-tag" v-for="(tag,idx) in item.tags" :key="idx"
						:style="[tag.type === 'hot'?{'border-color':'#f499a8',color:'#d00a2b'}:{'border-color':'#999999',color:'#000000'},{'max-width': item.tags.length>1?'148rpx':'100%'}]">
						<text>{{tag.name}}</text>
					</view>
				</view> -->
				<view class="t-goods-price">
					<text class="t-p1">¥{{item.productprice}}</text>
					<text class="t-p2"><text>已售{{item.productselled}}只</text></text>
					<view class="t-p3" v-show="!props.isFav" @click="addFavouriteData(item.id,item.productname)"><u-icon name="star" color="#ff6600" size="26"></u-icon></view> 
					<!-- <text class="t-p2">¥{{item.goodsOriginPrice}}</text> -->
				</view>
				<!-- <view class="t-rate w-full">
					<view><text>已售{{item.rateNum}}只</text></view>
					<view class="t-rate-percent"><text>{{item.ratePercent}}好评</text></view>
				</view>	 -->				
			</view>
		</view>
		<view class="t-empty" v-else>
			<image src="/static/goods.png"></image>
			<view class="t-empty-desc">没有商品哦~</view>
		</view>
		<view class="t-loading-more" v-if="isLoading || isNoMore && goodsList.data && goodsList.data.length>0">
			<block v-if="isShowLoading">
				<image src="../../static/loading.png" v-if="isLoading"></image>
				<view class="t-loading-desc" v-if="isLoading || isNoMore">{{isLoading?'加载中...':(isNoMore?'没有更多数据了':'')}}</view>
			</block>
		</view>
		

		
	</view> <!-- content End -->	
</template>

<script setup lang='ts'>
import { ref,reactive,onMounted,watch } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { addFavouriteData,getAllProducts,searchProducts } from '@/utils/apiFunction'
/* import type {storeType} from '@/utils/utils' */
import {storeSet,storeGet,GoUrl} from '@/utils/utils'
import { userStore } from '@/stores/userStore'	
const userstore = userStore();

//商品列表
let goodsList=reactive<any>({data:[]});
//页码，从1开始
let pageNo=ref(1);
//每页数据
let pageSize=ref(10);
//是否没有更多数据了
let isNoMore=ref(false);
//是否加载中
let isLoading=ref(false);
//是否初始化完成
let isInit=ref(false);




const props=defineProps({
	isShowLoading:{
		type:Boolean,
		default:true
	},
	changIndex:{
		type:Number,
		default:0	
	},
	priceUp:{
		type:Boolean,
		default:true		
	},
	isFav:{ //是否我的收藏下 浏览痕迹
		type:Boolean,
		default:false		
	},
	keyWord:{
		type:String,
		default:""
	}
})

/* const emit = defineEmits<{
		(event : 'change', value : number) : void,
		(event : 'close', value : boolean) : boolean,
		(event : 'success', value : string) : void
}>() */


watch(()=>props.priceUp,(newIndex,oldIndex) => {
	goodsList.data=sortProductList(2);
});


watch(()=>props.changIndex,(newIndex,oldIndex) => {
		console.log("切换发生了变化:",newIndex,oldIndex);
		
		if(newIndex==0){ //综合
			getProductsList(); //获取全部产品信息
			return;
		}
		
		if(newIndex==1){ //最新
			goodsList.data=sortProductList(1);
			console.log("按最新id排序",goodsList.data)
		}	
			
		if(newIndex==2){ //价格
			goodsList.data=sortProductList(2);
			console.log("按价格排序")
		}	
		
		if(newIndex==3){ //销量
			goodsList.data=sortProductList(3);
			console.log("按销量排序")
		}			
		
	  },
	  { deep: true }
);

watch(()=>props.keyWord,(newval,oldval) => {
		console.log("搜索关键字发生了变化:",newval,oldval)
		if(/\S/.test(newval)==true && newval!='all'){ //有值并且不等于'all'
			searchProducts(newval).then(res=>{
				console.log("开始搜索关键字商品",res);
				if(res.data.code===200){
					//给商品列表赋值
					goodsList.data = res.data.data;
				}
			});
		}else{
			//搜索无结果，则获取全部商品不能返回空
			getProductsList();
		}			
	  },
	  { deep: true }
);

//清空所有记录
const clearAllHistory=()=>{
	uni.showModal({
		title: '操作提示',
		content: '是否清空所有浏览记录',
		showCancel: true,
		success:async res => {
			if(res.confirm){
				userstore.clearAllHistory();
				goodsList.data=[];
			}
		},
		fail: () => {},
		complete: () => {}
	});
}

const getProductsList=()=>{
	//去请求服务器获取商品列表数据
	isLoading.value = true;
	getAllProducts().then(res=>{
		//从一定时间内缓存中读取商品，不用重复读取数据库
		let storeData:any=storeGet("goodsList");
		if(storeData!=null && storeData!=''){
			goodsList.data=storeData;
			//初始化完成
			isInit.value = true;
			//关闭加载动画
			isLoading.value = false;
			console.log("从缓存读取数据")
			return;
		}
		console.log("从数据库读取产品信息",res)
		if(res.data.code===200){
			//给商品列表赋值
			goodsList.data = res.data.data;
			//缓存商品信息
			storeSet("goodsList",goodsList.data,300*1000); //1000 * 60 * 5 =300*1000秒=300秒=5分钟
			//初始化完成
			isInit.value = true;
			//关闭加载动画
			isLoading.value = false;
			//如果第一次请求数据量少于pageSize说明只有一页，直接显示没有更多数据
			if (!goodsList || goodsList.length < pageSize.value) {
				isNoMore.value = true;
			}
	    }
	});	
}



//返回排序后的产品
const sortProductList=(index:number)=>{
	if(index===0) return goodsList.data;
	if(goodsList.data==null || goodsList.data.length<=0){
		getProductsList(); //如果没有数据，获取一次商品信息
		return null;
	}
	switch(index){
		case 1:
			//按最新排序
		   goodsList.data=goodsList.data.sort((objA:any, objB:any)=>{ 
				return objB.id - objA.id; //降序排列
			});
		break;
		case 2:
			//按价格排序
		   goodsList.data=goodsList.data.sort((objA:any, objB:any)=>{ 
				return props.priceUp?objB.productprice - objA.productprice:objA.productprice - objB.productprice; //降序排列
			});
		break;
		case 3:
			//按销量排序
		   goodsList.data=goodsList.data.sort((objA:any, objB:any)=>{ 
				return objB.productselled - objA.productselled; //降序排列 
			});
		break;
		default:
			return goodsList.data;
	}
	return goodsList.data;
}








onMounted(()=>{
	console.log("onMounted加载");
	//我的收藏-浏览痕迹模式
	if(props.isFav){
		console.log("浏览过的痕迹",userstore.lookProductHistory);
		if(userstore.lookProductHistory.length>0){
			goodsList.data=[];
			userstore.lookProductHistory.forEach(item=>{
				goodsList.data.push(item.productInfo);
			})
		}
	}
	
	//获取商品信息
	//getProductsList();
	
	//这里模拟加载到的商品列表如下
	/* setTimeout(() => {
		const res =reactive<any>([{
				goodsId:1,
				goodsPic: '/static/goods/11.jpg',
				goodsName: 'Helmetphone MT1 Neo智能骑行头盔(山地/框宽度）',
				goodsDesc: '一键语音',
				tags: [{
					name: '限时直降300元',
					type: 'hot'
				} , {
					name: '赠积分',
					type: 'default'
				}],
				goodsPrice: 599,
				goodsOriginPrice: 899,
				rateNum: 1068,
				ratePercent: '99%'
			},
			{
				goodsId:2,
				goodsPic: '/static/goods/12.jpg',
				goodsName: '海德HEAD智能跳绳S1双绳版',
				goodsDesc: '结合WATCH GT3等穿戴设备一起使用',
				tags: [{
					name: '限时直降300元',
					type: 'hot'
				}],
				goodsPrice: 399,
				goodsOriginPrice: 699,
				rateNum: 56,
				ratePercent: '98%'
			}
		]);
		//给商品列表赋值
		goodsList = res;
		//初始化完成
		isInit.value = true;
		//关闭加载动画
		isLoading.value = false;
		//如果第一次请求数据量少于pageSize说明只有一页，直接显示没有更多数据
		if (!goodsList || goodsList.length < pageSize.value) {
			isNoMore.value = true;
		}
	}, props.isShowLoading?1500:0); */
})

//页面滑动到底部监听--刷新下一页
onReachBottom(()=>{
	
	//我的收藏-浏览痕迹模式下不执行
	if(props.isFav) return;
	
	//这里模拟分页加载数据，数据总数为12条，2页
	//如果已经没有更多数据了，就不进行操作
	if (isNoMore.value) {
		return;
	}
	//否则进行请求
	isLoading.value = true;
	//页码加1
	pageNo.value += 1;
	//获取商品信息
	getProductsList();		
})


</script>

<style lang='scss' scoped>
	@import "Searchproduct.scss";
</style>